<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input v-model="queryParams.goodsName" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker v-model="queryParams.startTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item>
      <el-form-item label="结束时间" prop="entTime">
        <el-date-picker v-model="queryParams.entTime" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable size="small">
          <el-option label="未审核" :value="0"/>
          <el-option label="上架" :value="1"/>
          <el-option label="下架" :value="2"/>
          <el-option label="已结束" :value="3"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">添加折扣商品</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="id主键" align="center" prop="id" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品详情" align="center" prop="goodsInfo" />
      <el-table-column label="商品名称" align="center" prop="goodsName" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="entTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.entTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已售库存" align="center" prop="soldNum" />
      <el-table-column label="状态" align="center" prop="status" >
        <template v-slot="scope">
          <span>{{ groupGoodsOrder[scope.row.status] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['qd:dis-goods:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['qd:dis-goods:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="80%" v-dialogDrag append-to-body>
      <el-dialog
        width="60%"
        title="商品"
        :visible.sync="innerVisible"
        @close="productRefcColse"
        append-to-body>
        <el-table ref="productRef" :data="Goodslist" @selection-change="productSelection">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="id" align="center" prop="id"/>
          <el-table-column label="商品名称" align="center" prop="name"/>
          <el-table-column label="图片" align="center" prop="img">
            <template v-slot="scope">
              <div class="imgbox" v-if="scope.row.img.length !== 0">
                <img class="imgstyle" :src="scope.row.img[scope.row.imgIndex]" alt="">
                <div class="toleftstyle" @click="toleft(scope.$index,scope.row.img.length,scope.row.imgIndex)"><i
                  class="el-icon-arrow-left"></i></div>
                <div class="torightstyle" @click="toright(scope.$index,scope.row.img.length,scope.row.imgIndex)"><i
                  class="el-icon-arrow-right"></i></div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品分类" align="center" prop="type">
            <template v-slot="scope">
              <span>{{ gettype(scope.row.type) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="销售数量" align="center" prop="saleNum"/>
          <el-table-column label="商品上架状态" align="center" prop="status">
            <template v-slot="scope">
              <el-tag :type="scope.row.status == 1 ? 'success' : 'info'" effect="dark">
                {{ statusobj[scope.row.status] }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="Goodslisttotal > 0" :total="Goodslisttotal" :page.sync="goodsQueryParams.pageNo"
                    :limit.sync="goodsQueryParams.pageSize"
                    @pagination="getGoodsList"/>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="pichangeimgSortConfirm">确 定</el-button>
          <el-button @click="innerVisible = false">取 消</el-button>

        </span>
      </el-dialog>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="goodsId">
          <el-select v-model="form.goodsId" :disabled="form.id" filterable remote reserve-keyword
                     placeholder="请输入关键词"
                     :remote-method="remoteMethod" @change="productNameChange">
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-button @click="lookProduct" style="margin-left:10px" type="primary">查看</el-button>
        </el-form-item>
        <el-form-item label="商品图片" prop="goodsInfo">
          <img style="width:100px;height:120px" :src="form.zhanimg" alt="">
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable v-model="form.startTime" type="date" value-format="timestamp" placeholder="选择开始时间" />
        </el-form-item>
        <el-form-item label="结束时间" prop="entTime">
          <el-date-picker clearable v-model="form.entTime" type="date" value-format="timestamp" placeholder="选择结束时间" />
        </el-form-item>
      </el-form>
      <el-table ref="myTable" :data="form.goodsInfo" border style="width: 70%">
          <el-table-column prop="" label="" type="expand" width="30">
            <template v-slot="scope">
              <el-table :data="scope.row.child" border style="width: 100%">
                <el-table-column prop="size" label="尺码">
                  <template v-slot="scop">
                    <div>
                      <el-input v-model="scop.row.size" disabled placeholder="请输入内容"></el-input>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="价格">
                  <template v-slot="scop">
                    <div>
                      <el-input v-model="scop.row.price" disabled placeholder="请输入内容"></el-input>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="num" label="库存数量">
                  <template v-slot="scop">
                    <div>
                      <el-input v-model="scop.row.num" disabled placeholder="请输入内容"></el-input>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="weight" label="重量">
                  <template v-slot="scop">
                    <div style="display:flex;align-items:center;">
                      <el-input v-model="scop.row.weight" disabled placeholder="请输入内容"></el-input>
                      <span style=" white-space: nowrap;">kg</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="groupPrice" label="拼团价格">
                  <template v-slot="scop">
                    <div>
                      <el-input v-model="scop.row.groupPrice" placeholder="请输入内容"></el-input>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="groupNum" label="拼团活动数量">
                  <template v-slot="scop">
                    <div>
                      <el-input v-model="scop.row.groupNum" placeholder="请输入内容"></el-input>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="url" label="图片">
            <template v-slot="scope">
              <div>
                <img style="width:50px;height:50px;" :src="scope.row.url" alt="">
              </div>
            </template>
          </el-table-column>
        </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { createDisGoods, updateDisGoods, deleteDisGoods, getDisGoods, getDisGoodsPage, exportDisGoodsExcel } from "@/api/qd/disGoods";
import {getGoodsPage} from "@/api/qd/goods";

export default {
  name: "DisGoods",
  components: {
  },
  data() {
    return {
      //选择商品表格
      productOptions: [],
      Goodslisttotal: 0,
      multipleSelection:[],
      Goodslist: [],
      innerVisible: false, // 内嵌商品表格渲染
      goodsQueryParams: {
        pageNo: 1,
        pageSize: 10,
      },
      statusobj: {1: '上架', 2: '下架'},

      //活动状态 0未审核1上架2下架3已结束
      groupGoodsOrder: {0: '未审核', 1: '上架', 2: '下架', 3: '已结束'},
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 折扣商品列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        createTime: [],
        goodsId: null,
        goodsInfo: null,
        goodsName: null,
        startTime: [],
        entTime: [],
        soldNum: null,
        status: null,
      },
      options: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsId: [{ required: true, message: "商品不能为空", trigger: "blur" }],
        startTime: [{ required: true, message: "开始时间不能为空", trigger: "blur" }],
        entTime: [{ required: true, message: "结束时间不能为空", trigger: "blur" }],
      }
    };
  },
  created() {
    this.getList();
    this.getGoodsList()
    this.fenleiList()
  },
  methods: {
    lookProduct() { // 查看商品
      this.innerVisible = true;
    },
    productNameChange(e) {
      // this.form
      const obj = this.productOptions.find(item => item.id === e)
      if (obj.img && obj.img.length !== 0) this.$set(this.form, 'zhanimg', obj.img[0])
      this.$set(this.form, 'goodsInfo', obj.specif ?? [])
      if (obj.specif && obj.specif.length !== 0) this.productopen()
    },
    remoteMethod(value) { // 查询商品
      this.$axios({url: '/qd/group-goods/findByName', method: 'get', params: {name: value}}).then(res => {
        this.productOptions = res.data ?? []
      })
    },
    pichangeimgSortConfirm() {
      if (this.multipleSelection.length !== 1) return this.$message.warning('请选中一种商品')

      const obj = this.multipleSelection[0]
      if (obj.img && obj.img.length !== 0) this.$set(this.form, 'zhanimg', obj.img[0])
      this.productOptions.push({...obj})
      if (obj.specif && obj.specif.length !== 0) this.productopen()
      this.$set(this.form, 'goodsId', obj.id ?? '')
      this.$set(this.form, 'goodsInfo', obj.specif ?? [])
      this.innerVisible = false
    },
    productopen() { // 打开表格下拉
      this.$nextTick(() => {
        this.$refs.myTable.toggleRowExpansion(this.form.goodsInfo[0], true)
      })

    },
    getGoodsList() {
      //  获取商品数据
      getGoodsPage(this.goodsQueryParams).then(response => {
        this.Goodslist = response.data.list ?? [];
        this.Goodslist.forEach(item => {
          this.$set(item, 'imgIndex', 0)
          this.$set(item, 'check', false)
        })
        this.Goodslisttotal = response.data.total;
        this.loading = false;
      });
    },
    fenleiList() {
      // 获取商品分类数据
      this.$axios({url: 'qd/goodsType/getTree', method: 'get'}).then(res => {
        this.options = res.data ?? []
        // 删除第三层级的children
        this.options.forEach(item => {
          item.children.forEach(ite => {
            ite.children.forEach(it => {
              delete it.children
            })
          })
        })
      })
    },
    productRefcColse() {
      this.$refs.productRef.clearSelection()
    },
    productSelection(val) {
      this.multipleSelection = val;
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getDisGoodsPage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    gettype(str) {  //根据商品类型id获取值
      let a = '', b = '', c = ''
      if (str) {
        let arr = str.split(',')
        this.options.forEach(item => {
          if (item.value === Number(arr[0])) {
            a = item.label ?? ''
            item.children.forEach(ite => {
              if (ite.value === Number(arr[1])) {
                b = item.label ?? ''
                ite.children.forEach(it => {
                  if (it.value === Number(arr[2])) {
                    c = it.label ?? ''
                  }
                })
              }
            })
          }
        })
      }
      return a + b + c
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        goodsId: undefined,
        goodsInfo: undefined,
        goodsName: undefined,
        startTime: undefined,
        entTime: undefined,
        soldNum: undefined,
        status: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加折扣商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getDisGoods(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改折扣商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateDisGoods(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createDisGoods(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除折扣商品编号为"' + id + '"的数据项?').then(function() {
          return deleteDisGoods(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有折扣商品数据项?').then(() => {
          this.exportLoading = true;
          return exportDisGoodsExcel(params);
        }).then(response => {
          this.$download.excel(response, '折扣商品.xls');
          this.exportLoading = false;
        }).catch(() => {});
    }
  }

};
</script>
<style lang="scss" scoped>
@import "../../styles/minImgStyle.scss";

.flexs {
  display: flex;
  justify-content: space-between;
}
</style>
